import CommonApi from '#/api/common/common'

import type { QrCodeParams } from '#/api/common/model/Common'

import { downloadFileFromImageUrl } from '@vben/utils'
import type { AnyFn } from '@vueuse/core'
import { Image } from 'ant-design-vue'
import { useMessage } from './useMessage'

export function useDownloadMPCode() {
    async function showMPCodePopup(
        opts: QrCodeParams,
        others: {
            api: AnyFn
            isCache: boolean
        }
    ) {
        const { createMessage, createConfirm } = useMessage()
        try {
            createMessage.loading({
                content: '生成中',
                duration: 3000
            })
            const res = await CommonApi.inst.getMPCodeUrl(opts, {
                api: others.api,
                isCache: others.isCache
            })
            createMessage.destroy()
            createConfirm({
                iconType: 'info',
                title: '查看小程序码',
                width: 480,
                okText: '下载',
                content: (
                    <div class="p-2 pb-5 pt-6">
                        <Image src={res} width={350} />
                    </div>
                ),
                async onOk() {
                    downloadFileFromImageUrl({
                        fileName: opts.fileName ?? `小程序码_${Date.now()}`,
                        source: res
                    })
                }
            })
        } catch {
            createMessage.destroy()
        }
    }

    return {
        showMPCodePopup
    }
}
